#include "RingQueue.hpp"
#include "Task.hpp"
#include <pthread.h>
#include <unistd.h>
#include <time.h>

void *Consumer(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args); // 生产者和消费者同时看到了一份公共资源

    while(true)
    {
        sleep(1);

        Task t;
        rq->Pop(&t);
        t.Run();
        std::cout << "consumer data: " << t.PrintResult() << std::endl;
    }

    return nullptr;
}

void *Productor(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);

    while(true)
    {
        // 1. 准备数据
        int data1 = rand() % 10;
        usleep(rand() % 123);
        int data2 = rand() % 10;
        usleep(rand() % 123);
        char oper = opers[rand() % opers.size()];
        Task t(data1, data2, oper);

        // 2. 进行生产
        rq->Push(t);

        // for debug
        std::cout << "productor data: " << t.PrintTask() << std::endl;
    }

    return nullptr;
}

int main()
{
    // 种下随机数种子
    srand((uint16_t)time(nullptr) ^ getpid() ^ pthread_self()); 

    pthread_t c[3], p[2];

    RingQueue<Task> *bq = new RingQueue<Task>();

    pthread_create(&p[0], nullptr, Productor, (void*)bq);
    pthread_create(&p[1], nullptr, Productor, (void*)bq);
    pthread_create(&c[0], nullptr, Consumer, (void*)bq);
    pthread_create(&c[1], nullptr, Consumer, (void*)bq);
    pthread_create(&c[2], nullptr, Consumer, (void*)bq);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(c[2], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);

    return 0;
}